package com.liu.shiro.controller;

import com.liu.shiro.entity.JsonData;
import com.liu.shiro.entity.User;
import com.liu.shiro.entity.UserQuery;
import com.liu.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("pub")
public class PublicController {

    @Autowired
    private UserService userService;

    @RequestMapping("/need_login")
    public JsonData needLogin(){

        return JsonData.buildSuccess("温馨提示：请先登录对应账号！",-2);
    }

    @RequestMapping("/not_permit")
    public JsonData notPermit(){

        return JsonData.buildSuccess("温馨提示：您没有对应权限，拒绝访问！",-3);
    }

    @RequestMapping("/index")
    public JsonData index(){
        List<String> videoList = new ArrayList<>();
        videoList.add("新一代微服务全家桶AlibabaCloud+SpringCloud实战");
        videoList.add("玩转新版高性能RabbitMQ容器化分布式集群实战");
        videoList.add("三天掌握 Kafka 消息队列 小白到专家之路-大数据教程");
        videoList.add("小白到专家-分布式缓存Redis6.X+高可用集群");
        videoList.add("新一代流式计算框架 Flink视频教程java大数据");

        return JsonData.buildSuccess(videoList,"success");
    }

    @PostMapping("/login")
    public JsonData login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){

        Subject subject = SecurityUtils.getSubject();

        Map<String, Object> info = new HashMap();

        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            subject.login(usernamePasswordToken);
            info.put("msg","登录成功");
            info.put("session_id",subject.getSession().getId());
            return JsonData.buildSuccess(info);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonData.buildError("账号登录失败！");
        }
    }


    @RequestMapping("finduserinfo")
    public Object findUserInfo(@RequestParam("username")String username){

        return userService.findAllUserInfoByUsername(username);
    }

}
